const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
var QQMapWX = require('../../../lib/qqmap-wx-jssdk.min.js');
var qqmapsdk;
//获取应用实例
const app = getApp();
var page;
var that;
Page({
  data: {
    banner: [],
    picIndex: 0,
    hasSpareRooms: true,
    equips: [],
    unitInfo: {},
    disObj: {
      status: true,
      disTxt: '计算中......',
    },
    housesRes: [],
    units:[],
    roomTypes: {},
    deviceIds: [],
    homeownersNo: '',
    dialog: true,
    poster: ''
  },
  onLoad: function (options) {
    that = this;
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'BJFBZ-ZFTHW-Y2HRO-RL2UZ-M6EC3-GMF4U'
    });
    page = util.page.clone();
    app.getBaseEnums().then(baseEnums => {
      var ids = baseEnums.deviceLs.map(function (i, n) {
        return i.id;
      });
      that.setData({
        baseEnums: baseEnums,
        roomTypes: baseEnums.roomTypes,
        deviceIds: ids,
      });
    });
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(options.scene);
    if (options.id){
      scene = options.id;
    }
    that.setData({
      "homeownersNo": scene
    });
    app.globalData.ownersNo = scene;
    that.getIndexData();
  },
  getIndexData(){
    that.commInitData(api.ShareFromLandlord, { "homeownersNo": that.data.homeownersNo, isAllow:true});
  },
  commInitData(url, params = {}) {
    app.post(url, params, { retry: 3 }).then(rsp => {
      var rlt = rsp.data;
      if (rlt) {
        Object.keys(rlt).forEach(function (k, n) {
          if (k == 'unitArray') {
            that.data.units = rlt[k];
            that.data.units.forEach(function(v,index){
              if (v.house && v.house.length>0){
                v.house.forEach(function(a,b){
                  a.unitName = v.unitName;
                  a.unitCoordinates = v.unitCoordinates;
                  a.unitAddress = v.unitAddress;
                  a.principalMobile = rlt.principalMobile;
                  that.data.housesRes.push(a);
                });
              }
            });
          } else {
            that.data.unitInfo[k] = rlt[k];
          }
        });
        if (page.isLoad(that.data.housesRes)) {
          page.next();
        }
        that.data.housesRes.forEach(function (i, n) {
          if (i.photoUrl && i.photoUrl.indexOf('/') != -1) {
            i.imgs = i.photoUrl.split(',').map(function (v, k) {
              return app.showImg(v);
            });
          }
          //房间租金分转元
          i.rentAmount = (i.rentAmount / 100).toFixed(2);
          if (i.rentAmount == parseInt(i.rentAmount)) {
            i.rentAmount = parseInt(i.rentAmount);
          }
          //设备列表
          var deviceList = JSON.parse(i.deviceList);
          deviceList.forEach(function (ii, n) {
            var deviceIndex = that.data.deviceIds.indexOf(ii.id);
            if (deviceIndex != -1){
              ii.text = that.data.baseEnums.deviceLs[deviceIndex].typeName;
            }
          });
          i.deviceList = deviceList;
        });
        //console.log('hosuesRes', that.data.housesRes);
        that.setData({
          housesRes: that.data.housesRes,
          unitInfo: that.data.unitInfo
        });
        //计算两点间的距离
        /*
        let unitCoordinates = that.data.unitInfo.unitCoordinates;
        if (unitCoordinates && unitCoordinates.indexOf(',') == -1) {
          util.toast.fail('单元经纬度错误');
        } else {
          let latitude = Number(unitCoordinates.split(',')[0]);
          let longitude = Number(unitCoordinates.split(',')[1]);
          that.distance(latitude, longitude);
        }*/
        //信息认证单元照片
        if (that.data.unitInfo.housePhoto && that.data.unitInfo.housePhoto.indexOf('/') != -1) {
          that.data.unitInfo.housePhoto.split(',').forEach(function (i, n) {
            that.data.banner.push(app.showImg(i))
          });
          that.setData({
            banner: that.data.banner
          });
        }
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  distance(lat, lon) {
    //1、获取当前位置坐标
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        qqmapsdk.calculateDistance({
          mode: 'driving',
          from: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          to: [{
            latitude: lat,
            longitude: lon
          }],
          success: function (res) {
            console.log('distance', res);
            var disTxt = 'm';
            if (res.status == 0) {
              var rlt = res.result.elements[0];
              var dis = rlt.distance; //单位m
              if (dis > 1000) {
                disTxt = (dis / 1000).toFixed(2) + 'km';
              } else {
                disTxt = dis.toFixed(2) + disTxt;
              }
            } else {
              var error = {
                310: '请求参数信息有误',
                31: 'key格式有误',
                306: '请求有护持信息,请检查字符串',
                110: '请求来源未被授权',
              };
              disTxt = error[res.status];
              if (!disTxt) {
                disTxt = '未知异常';
              }
              that.setData({
                'disObj.status': false
              });
            }
            that.setData({
              'disObj.disTxt': disTxt
            });
          },
          fail: function (res) {
            console.log(res);
            that.setData({
              'disObj.status': false,
              'disObj.disTxt': '距离计算失败'
            });
          }
        });
      }
    })
  },
  intoRoomDetail(e) {
    var id = e.currentTarget.id;
    var room = that.data.housesRes[id];
    var params = 'houseNo=' + room.houseNo + '&coordinates=' + room.unitCoordinates + '&mobile=' + room.principalMobile + '&unitAddress=' + room.unitAddress + '&homeownersNo=' + that.data.homeownersNo +'&unitName='+room.unitName;
    wx.navigateTo({
      url: '/pages/houseRes/share/detail?' + params,
    })
  },
  onPullDownRefresh() {
    page.reset();
    that.setData({
      banner: [],
      picIndex: 0,
      housesRes: [],
      unitInfo: {}
    });
    that.getIndexData();
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    that.toDoHouseRes();
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.banner // 需要预览的图片http链接列表
    })
  },
  toDoHouseRes: function () {
    let params = { homeownersNo: that.data.homeownersNo, isAllow:true};
    app.loadPagePost(api.GetShareHouseRes, page, params).then(rsp => {
      //console.log('rspppppp',rsp);
      var units = rsp;
      if (units.length > 0) {
        var tempHouse = [];
        units.forEach(function (v, index) {
          if (v.house && v.house.length > 0) {
            v.house.forEach(function (i, n) {
              i.unitName = v.unitName;
              i.unitCoordinates = v.unitCoordinates;
              i.unitAddress = v.unitAddress;
              i.principalMobile = that.data.unitInfo.principalMobile;
              if (i.photoUrl && i.photoUrl.indexOf('/') != -1) {
                i.imgs = i.photoUrl.split(',').map(function (v, k) {
                  return app.showImg(v);
                });
              }
              //房间租金分转元
              i.rentAmount = (i.rentAmount / 100).toFixed(2);
              if (i.rentAmount == parseInt(i.rentAmount)) {
                i.rentAmount = parseInt(i.rentAmount);
              }
              //设备列表
              var deviceList = JSON.parse(i.deviceList);
              deviceList.forEach(function (ii, n) {
                var deviceIndex = that.data.deviceIds.indexOf(ii.id);
                ii.text = app.baseEnums.deviceLs[deviceIndex].typeName;
              });
              i.deviceList = deviceList;
              tempHouse.push(i);
              that.data.housesRes.push(i);
            });
          }
        });
        if (page.isLoad(tempHouse)) {
          page.next();
        }
      }
      that.setData({
        housesRes: that.data.housesRes
      });
    }).catch((err) => {
      console.log(err);
    });
  },
  picChange(e) {
    that.setData({
      picIndex: e.detail.current
    });
  },
  callPhone(e) {
    var phoneNumber = that.data.unitInfo.principalMobile;
    if (phoneNumber) {
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        fail() { }
      })
    } else {
      util.toast.fail('手机号不存在');
    }
  },
  //分享功能
  onShareAppMessage: function (res) {
    //分享的类型为按键类型
    if (res.from == "button") {
      return {
        title: '这里的房间实惠啊,快来看看吧！！！',
        path: 'pages/houseRes/share/list?scene=' + encodeURIComponent(that.data.homeownersNo),
        success: function (res) { }
      }
    }
  },
  nearbyHouseRes() {

  },
  iCCall() { //一键导航
    let unitCoordinates = that.data.unitInfo.unitCoordinates;
    if (unitCoordinates && unitCoordinates.indexOf(',') == -1) {
      util.toast.fail('经纬度错误');
      return false;
    }
    let latitude = Number(unitCoordinates.split(',')[0]);
    let longitude = Number(unitCoordinates.split(',')[1]);
    let name = that.data.unitInfo.unitAddress;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图定位功能将无法使用',
            success: function (res) {
              if (res.cancel) {
                console.info("1授权失败返回数据");
              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      wx.openLocation({
                        latitude: latitude,
                        longitude: longitude,
                        name: name,
                        scale: 28
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: name,
            scale: 28
          })
        }
      }
    })
  },
  shareHouseRes() {
    /*
    app.postForm(api.GetHouseResQr, { scene: 'p=3&pp=4', page: '' }).then(rsp => {
      that.setData({
        poster: app.showImg(rsp.data.filePath),
        dialog: !that.data.dialog,
      });
    });*/
    var scene = encodeURIComponent(that.data.homeownersNo);
    var page = 'pages/houseRes/share/index';
    that.setData({
      poster: api.GetShareHouseResQr + '?scene=' + scene + '&page=' + page + '&ownersNo=' + that.data.homeownersNo +'&time=' + new Date(),
      dialog: !that.data.dialog,
    });
  },
  /**
  * 页面卸载删除海报，以免造成垃圾文件暂用服务器资源
  */
  onUnload: function () {
    //that._delPoster();
  },
  _delPoster: function () {
    app.removeFile(that.data.poster);
  },
  closeShare: function () {
    that.setData({
      dialog: !that.data.dialog
    });
    //that._delPoster();
  },
  downLoad() {
    wx.showLoading({
      title: '图片下载中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000);
    var imgurl = that.data.poster;
    imgurl = imgurl.substr(0, imgurl.lastIndexOf('&')) + '&abc.png';
    wx.downloadFile({
      url: imgurl,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (ret) {
            wx.showToast({ title: '保存图片成功' });
          },
          fail: function (ret) {
            util.toast.fail('保存图片失败');
          }
        })
      }
    })
  },
  // 点击保存图片
  savePicture: function () {
    let that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.downLoad();
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用
              that.downLoad();
            },
            fail: function () {
              /*获取权限时点击了拒绝以后的弹窗*/
              if (wx.canIUse('button.open-type.openSetting')) {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请点击重新授权进入开启授权。',
                  confirmText: '重新授权',
                  cancelText: '取消',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function (data) {
                          if (data.authSetting["scope.writePhotosAlbum"] == true) {
                            util.toast.success('授权成功');
                            that.downLoad();
                          } else {
                            util.toast.fail('授权失败');
                          }
                        }
                      })
                    }
                  }
                })
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请删除小程序重新进入。'
                })
              }
            }
          })
        }
      }
    })
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})
